package com.dba.example.gwt.client.commands;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestBuilder.Method;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Command;

public abstract class RequestBuilderCommand implements Command {

	protected void getRequest(String url) {
		sendRequest(RequestBuilder.GET, url, null);
	}
	
	protected void postRequest(String url, String requestData) {
		sendRequest(RequestBuilder.POST, url, requestData);
	}
	
	protected void sendRequest(Method method, String url, String requestData) {
		RequestBuilder builder = new RequestBuilder(method, url);
		builder.setHeader("Accept", "application/json"); // or it could be application/xml;
		builder.setHeader("Content-Type", "application/json");
		Request request = null;
		
		try {
			request = builder.sendRequest(requestData, new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					error(request, exception);
				}

				public void onResponseReceived(Request request,
						Response response) {
					if (200 == response.getStatusCode()) {
						try {
							success(response.getText());
						} catch (Exception e) {
							error(request, e);
						}
					} else {
						error(request, null);
					}
				}
			});
		} catch (RequestException e) {
			error(request, e);
		}
	}
	
	public void success(String value) {
		
	}

	public void error(Request request, Throwable exception) {
		
	}

}
